import SoundManager from "../../../../core/sound_manager";
import Utils, { Random } from "../../../../core/utils";
import SubBody, { SubBodyEventContact, SubBodyEventType } from "../../../box2d_utils/sub_body";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Ball extends cc.Component {
    subBody: SubBody = null;
    @property(cc.Prefab)
    spakPrefab: cc.Prefab = null;
    @property
    speedLimitation = false;
    @property
    limitSpeed = 999;

    protected onLoad(): void {
        this.subBody = this.getComponent(SubBody);
        this.subBody.on(SubBodyEventContact, this.onContact, this);
    }
    onContact(evt: SubBodyEventContact) {
        if (evt.type === SubBodyEventType.Begin) {
            SoundManager.ins.playClip(`hit${Random.range(1, 7)}`, false, 0.4);
            let spak = cc.instantiate(this.spakPrefab);
            let pt = evt.contact.getManifold().points[0];
            if (pt) {
                let pac = spak.getComponent(cc.ParticleSystem);
                let normal = evt.contact.getManifold().localNormal;
                if (!normal.equals(cc.Vec2.ZERO)) {
                    pac.angle = -90 - cc.misc.radiansToDegrees(normal.signAngle(cc.Vec2.UP));
                    pac.angleVar = 45;
                }
                else {
                    pac.angle = 0;
                    pac.angleVar = 360;
                }
                spak.setPosition(pt.localPoint.add(cc.v2(this.node.position)));
                this.node.parent.addChild(spak);
            }
        }
    }
    protected onDestroy(): void {
        SoundManager.ins.playClip("ball-in");
    }

    protected lateUpdate(dt: number): void {
        if (this.speedLimitation) {
            let dv = this.subBody.body.linearVelocity;
            if (dv.len() > this.limitSpeed) {
                this.subBody.body.linearVelocity = dv.normalize().mul(this.limitSpeed);
            }
        }
    }
};